package org.example.jdbc_study.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户socket
 *
 * @author 欧阳劲驰
 * @since 0.0.1
 */
public class SocketClient {
    /**
     * 主函数
     *
     * @param args 上下文
     */
    public static void main(String[] args) {
        //获取socket
        try (Socket socket = new Socket("127.0.0.1", 10040)) {
            //输出线程
            Thread outputThread = new Thread(() -> {
                try {
                    while (!socket.isClosed()) {
                        //获取键盘输入
                        Scanner scanner = new Scanner(System.in);
                        //获取键盘数据
                        System.out.println("请输入");
                        String next = scanner.next();
                        //获取输出流
                        OutputStream outputStream = socket.getOutputStream();
                        //发送数据
                        outputStream.write(next.getBytes());
                        System.out.println("发送数据:" + next);
                        //刷新缓冲
                        outputStream.flush();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            //输入线程
            Thread inputThread = new Thread(() -> {
                try {
                    while (!socket.isClosed()) {
                        //获取输入流
                        InputStream inputStream = socket.getInputStream();
                        //读取输入流
                        byte[] b = new byte[1024];
                        int r = inputStream.read(b);
                        //如读取到数据则进行解析
                        if (r > -1) {
                            //从字节数组0至length读取,并输出
                            System.out.println("获取到字符串:" + new String(b, 0, r));
                        } else {
                            System.out.println("断开连接");
                            socket.close();
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            //启动子线程
            outputThread.start();
            inputThread.start();
            //主线程等待子线程
            outputThread.join();
            inputThread.join();
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
        }
    }
}
